
import {
  SendOutlined,
  PlusCircleOutlined,
  EditOutlined
} from '@ant-design/icons';
import {
  Button,
  message,
  Space,
  Popconfirm,
  Switch,
  Tag,
  Drawer,
  Layout, Pagination, Menu,
  Input, Spin
} from 'antd';
import { ProDescriptions } from '@ant-design/pro-components';
import React, { useState, useRef } from 'react';
import { useAccess, Access } from 'umi';
import SaveForm from './components/SaveForm';
import PermissionAssignment from './components/PermissionAssignment';
import PermissionAssignmentTable from './components/PermissionAssignmentTable';
import { query, update, add, get, statusChange } from './service';
import { useRequestHandle } from '@/utils/utils';
import operation from './operation';
import styles from './index.less';
import { useUpdateEffect } from '@umijs/hooks';
import { useEffect } from 'react';

const { Sider, Content } = Layout;
const { Search } = Input;
const RoleManage = () => {
  const pageSize = 11;

  const [updateFormValues, setUpdateFormValues] = useState({});
  const [hoveFormValues, setHoveFormValues] = useState({});
  const [distributionVisible, setDistributionVisible] = useState(false);
  const [distributionValue, setDistributionValue] = useState({});
  const [loading, setLoading] = useState(false);

  const actionRef = useRef();
  const [row, setRow] = useState();
  const { canOperation } = useAccess();

  const [saveFormVisible, setSaveFormVisible] = useState(false);
  const [pageResult, setPageResult] = useState({
    current: 1,
    items: [],
    itemsPerPage: 15,
    totalItems: 0,
    totalPages: 0,
  });
  const [pageSearch, setPageSearch] = useState({
    current: 1,
    pageSize: 15,
    keyword: ""
  });

  // 刷新
  const reload = () => {
    if (actionRef.current) {
      actionRef.current.reload();

    }
    getPageRequest.run(pageSearch);
  };


  const getPageRequest = useRequestHandle(query, (data) => {
    if (!hoveFormValues.id) { setHoveFormValues(data.items[0]); }
    else {
      const item = data.items.find(item => item.id === hoveFormValues.id);
      if (item) {
        setHoveFormValues(item);
      }
    }
    setPageResult(data);
  });


  useUpdateEffect(() => {
    getPageRequest.run(pageSearch);
  }, [pageSearch]);

  useEffect(() => {
    async function init() {
      setLoading(true);
      const response = await query({ pageSize, pageIndex: 1 });
      setLoading(false);
      if (response && response.success) {
        if (response.data.items.length > 0) {
          setHoveFormValues(response.data.items[0]);
        }
        setPageResult(response.data);
      } else {
        message.error('获取应用列表失败！');
      }
    }
    init();
  }, []);

  // 新增
  const addRequest = useRequestHandle(add, () => {
    message.success('创建成功.');
    setSaveFormVisible(false);
    reload();
  });
  // 更新
  const updateRequest = useRequestHandle(update, () => {
    message.success('更新成功.');
    setSaveFormVisible(false);
    setUpdateFormValues({});
    reload();
  });

  // 状态变更
  const statusChangeRequest = useRequestHandle(statusChange, () => {
    message.success('操作成功.');
    reload();
  });



  // 操作-更多处理
  const moreOptionHandle = (key, record) => {
    switch (key) {

      case 'assign-permissions':
        setDistributionVisible(true);
        setDistributionValue({ id: record.id });
        break;
      default:
        break;
    }
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      fixed: 'left',
      width: 75,
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      ellipsis: true,
      render: (dom, entity) => <a onClick={() => setRow(entity)}>{dom}</a>,
      fixed: 'left',
      width: 200,
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      width: 100,
      render: (_, record) => {
        const isChecked = record.status === 1;
        const canChangeStatus = canOperation(operation.statusChange);
        if (!canChangeStatus) {
          return isChecked ? <Tag color="#87d068">启用</Tag> : <Tag color="#f50">禁用</Tag>;
        }
        const title = isChecked ? '确定要禁用该数据吗？' : '确定要启用该数据吗？';
        return (
          <>
            <Popconfirm
              placement="top"
              title={title}
              onConfirm={(e) => {
                e.stopPropagation();
                statusChangeRequest.run({ id: record.id });
              }}
              okText="确定"
              cancelText="取消"
            >
              <Switch
                loading={statusChangeRequest.loading}
                checkedChildren="启用"
                unCheckedChildren="禁用"
                checked={isChecked}
              />
            </Popconfirm>
          </>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      sorter: true,
      hideInForm: true,
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 175,
      render: (_, record) => (
        <Space>
          <Access accessible={canOperation(operation.update)}>
            <Button
              type="primary"
              size="small"
              onClick={async () => {
                const result = await get({ id: record.id });
                if (!result.success) {
                  message.error(result.message);
                  return;
                }
                setSaveFormVisible(true);
                setUpdateFormValues(result.data);
              }}
            >
              编辑
            </Button>
          </Access>

          <Access accessible={canOperation(operation.update)}>
            <Button
              type="primary"
              size="small"
              onClick={async () => {
                moreOptionHandle("assign-permissions", record);
              }}
            >
              <SendOutlined /> 分配权限
            </Button>
          </Access>


        </Space>
      ),
    },
  ];


  const getStatusChange = (record) => {
    const isChecked = record.status === 1;
    const canChangeStatus = canOperation(operation.statusChange) && record.roleType === 0;
    if (!canChangeStatus) {
      return isChecked ? <Tag color="#87d068">启用</Tag> : <Tag color="#f50">禁用</Tag>;
    }
    const title = isChecked ? '确定要禁用该数据吗？' : '确定要启用该数据吗？';
    return (
      <>
        <Popconfirm
          placement="top"
          title={title}
          onConfirm={(e) => {
            e.stopPropagation();
            statusChangeRequest.run({ id: record.id });
          }}
          okText="确定"
          cancelText="取消"
        >
          <Switch
            loading={statusChangeRequest.loading}
            checkedChildren="启用"
            unCheckedChildren="禁用"
            checked={isChecked}
          />
        </Popconfirm>
      </>
    );
  }

  const menuData = pageResult.items.map((item) => {
    return {
      key: item.id,
      label:


        <div>
          {item.name}<span style={{ color: "#937e00",marginLeft:"10px" }}> {item.roleType === 1 ? "系统管理员" : ""}</span>
          <span style={{ float: "right" }}>
            {getStatusChange(item)}
          </span>
        </div>,
    }
  })

  return (
    <Spin spinning={loading || getPageRequest.loading}>
      <Layout>
        <Sider width={300} className={styles.orgTree} theme="light">
          <div style={{ paddingBottom: "10px", borderBottom: "#cacaca30 1px solid" }}>
            <Button
              size='small'
              icon={<PlusCircleOutlined />}
              type="primary"
              style={{ margin: "10px 14px 0px" }}
              onClick={() => {
                setSaveFormVisible(true);
                setUpdateFormValues({});
              }}
            >
              添加角色
            </Button>

            <Button
              size='small'
              icon={<EditOutlined />}
              type="link"
              disabled={hoveFormValues.roleType !== 0}
              style={{ margin: "10px 14px 0px", float: "right" }}
              onClick={() => {
                setSaveFormVisible(true);
                setUpdateFormValues(hoveFormValues);
              }}
            >
              修改
            </Button>
          </div>
          <div style={{ padding: "10px 14px 5px" }}> <Search
            placeholder="请输入角色名称" onSearch={(e) => {
              setPageSearch({
                current: 1,
                pageSize,
                keyword: e
              });
            }} style={{ width: 272 }} /></div>
          <Menu
            onClick={(e) => {
              setHoveFormValues(pageResult.items.find(item => item.id === e.key));
            }}

            style={{ width: 300, padding: "4px 10px", border: "0" }}
            mode="inline"
            selectedKeys={[hoveFormValues.id]}
            items={[...menuData]}
          />

          {pageResult.totalPages > 1
            ? <Pagination
              style={{
                margin: "0 auto",
                borderTop: "1px solid #cacaca30",
                paddingTop: "10px",
                textAlign: "center", position: "absolute", bottom: "10px", left: "0", right: "0"
              }}
              simple
              onChange={(page, pageSize) => {
                setPageSearch({
                  current: page,
                  pageSize,
                });
              }}
              current={pageResult.current}
              total={pageResult.totalItems} /> : null
          }
        </Sider>
        <Content>
          <PermissionAssignmentTable
            onFinish={() => {
              setDistributionVisible(false);
              setDistributionValue({});
            }}
            record={hoveFormValues}
          />

        </Content>
        <SaveForm
          onSubmit={async (value) => {
            const params = Object.assign(value, { status: value.status ? 1 : 0 });
            if (params.id) {
              updateRequest.run(params);
            } else {
              addRequest.run(params);
            }
          }}
          onCancel={() => {
            setSaveFormVisible(false);
            setUpdateFormValues({});
          }}
          loading={updateRequest.loading || addRequest.loading}
          modalVisible={saveFormVisible}
          record={updateFormValues}
        />

        <Drawer
          width={600}
          open={!!row}
          onClose={() => {
            setRow(undefined);
          }}
          closable={false}
        >
          {row?.id && (
            <ProDescriptions
              column={2}
              title={row?.realName}
              request={async () => ({
                data: row || {},
              })}
              params={{
                id: row?.id,
              }}
              columns={columns}
            />
          )}
        </Drawer>



        <PermissionAssignment
          onCancel={() => {
            setDistributionVisible(false);
            setDistributionValue({});
          }}
          onFinish={() => {
            setDistributionVisible(false);
            setDistributionValue({});
          }}
          modalVisible={distributionVisible}
          record={distributionValue}
        />
      </Layout>
    </Spin>
  );
};

export default RoleManage;
